"""
控制系统音量的模块
支持获取当前音量和设置新的音量级别
"""

class SystemVolumeController:
    """系统音量控制器"""
    
    def __init__(self):
        """初始化音量控制器，检测并选择可用的音频控制系统"""
        self.audio_system = self._detect_audio_system()
    
    def _detect_audio_system(self):
        """检测系统使用的音频系统"""
        try:
            import pulsectl
            return "pulseaudio"
        except ImportError:
            try:
                import alsaaudio
                return "alsa"
            except ImportError:
                return "command"
    
    def get_volume(self):
        """获取当前系统音量（0.0-1.0范围内）"""
        if self.audio_system == "pulseaudio":
            return self._get_pulseaudio_volume()
        elif self.audio_system == "alsa":
            return self._get_alsa_volume()
        else:
            return self._get_volume_by_command()
    
    def set_volume(self, volume_level):
        """
        设置系统音量
        
        参数:
            volume_level: 音量级别，范围0.0-1.0
        """
        # 确保音量在有效范围内
        volume_level = max(0.0, min(1.0, volume_level))
        
        if self.audio_system == "pulseaudio":
            return self._set_pulseaudio_volume(volume_level)
        elif self.audio_system == "alsa":
            return self._set_alsa_volume(volume_level)
        else:
            return self._set_volume_by_command(volume_level)
    
    def _get_pulseaudio_volume(self):
        """获取PulseAudio系统音量"""
        try:
            import pulsectl
            with pulsectl.Pulse('volume-getter') as pulse:
                sink_list = pulse.sink_list()
                if sink_list:
                    # 获取默认音频设备的音量
                    return sink_list[0].volume.value_flat
                return 0.0
        except Exception as e:
            print(f"获取音量失败: {e}")
            return 0.0
    
    def _set_pulseaudio_volume(self, volume_level):
        """设置PulseAudio系统音量"""
        try:
            import pulsectl
            with pulsectl.Pulse('volume-setter') as pulse:
                sink_list = pulse.sink_list()
                if sink_list:
                    # 设置默认音频设备的音量
                    sink = sink_list[0]
                    pulse.volume_set_all_chans(sink, volume_level)
                    return True
            return False
        except Exception as e:
            print(f"设置音量失败: {e}")
            return False
    
    def _get_alsa_volume(self):
        """获取ALSA系统音量"""
        try:
            import alsaaudio
            mixer = alsaaudio.Mixer()
            volumes = mixer.getvolume()
            # 将百分比值转换为0-1范围
            return volumes[0] / 100.0 if volumes else 0.0
        except Exception as e:
            print(f"获取ALSA音量失败: {e}")
            return 0.0
    
    def _set_alsa_volume(self, volume_level):
        """设置ALSA系统音量"""
        try:
            import alsaaudio
            # 将0-1范围转换为百分比值
            volume_percent = int(volume_level * 100)
            mixer = alsaaudio.Mixer()
            mixer.setvolume(volume_percent)
            return True
        except Exception as e:
            print(f"设置ALSA音量失败: {e}")
            return False
    
    def _get_volume_by_command(self):
        """通过命令行获取系统音量"""
        import subprocess
        try:
            # 尝试使用amixer命令获取音量
            cmd = "amixer sget Master | grep 'Left:' | awk -F'[][]' '{ print $2 }'"
            output = subprocess.check_output(cmd, shell=True, text=True).strip()
            if output.endswith('%'):
                return float(output[:-1]) / 100.0
            return 0.0
        except:
            try:
                # 尝试使用pactl命令获取音量
                cmd = "pactl list sinks | grep Volume: | head -n 1 | awk '{print $5}'"
                output = subprocess.check_output(cmd, shell=True, text=True).strip()
                if output.endswith('%'):
                    return float(output[:-1]) / 100.0
                return 0.0
            except:
                print("无法通过命令行获取系统音量")
                return 0.0
    
    def _set_volume_by_command(self, volume_level):
        """通过命令行设置系统音量"""
        import subprocess
        volume_percent = int(volume_level * 100)
        
        try:
            # 尝试使用amixer命令设置音量
            subprocess.run(f"amixer sset Master {volume_percent}%", shell=True, check=True)
            return True
        except:
            try:
                # 尝试使用pactl命令设置音量
                subprocess.run(f"pactl set-sink-volume @DEFAULT_SINK@ {volume_percent}%", shell=True, check=True)
                return True
            except:
                print("无法通过命令行设置系统音量")
                return False


# 使用示例
if __name__ == "__main__":
    volume_controller = SystemVolumeController()
    
    # 获取当前音量
    current_volume = volume_controller.get_volume()
    print(f"当前系统音量: {current_volume:.2f}")
    
    # 设置音量为50%
    volume_controller.set_volume(1.0)
    print("已将系统音量设置为100%")
